import baidu_ai_common
import requests
import os

def main():
        
    folder_path = "文字识别/"
    file_names=os.listdir(folder_path)
    select_file_index=selectFile(file_names)
    recognition(folder_path+file_names[select_file_index])


def recognition(file_path):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + baidu_ai_common.get_access_token()
    
    payload='image='+baidu_ai_common.get_file_content_as_base64(file_path,True)
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    result_text=response.json()
    print('-----------------以下是识别结果-----------------')
    for words in result_text['words_result']:
        print(words['words'])


def selectFile(file_names):
    index=0
    for file_name in file_names:
        print(index,':',file_name)
        index+=1

    select_ok=0
    while select_ok==0:
        file_index=int(input('文字识别中包含以上文件，请您要识别的文件序号：'))
        if file_index not in range(0,len(file_names)):
            print('序号有误，请重新选择')
        else:
            select_ok=1

    return file_index

if __name__ == '__main__':
    main()